//
//  AudioPlayerHandle.m
//  AudioBook_A
//
//  Created by Sansan on 15/4/13.
//  Copyright (c) 2015年 Sansan. All rights reserved.
//

#import "AudioPlayerHandle.h"

@implementation AudioPlayerHandle

+ (instancetype)shareHandle
{
    static AudioPlayerHandle *audio = nil;
    if (audio == nil) {
        audio = [[AudioPlayerHandle alloc] init];
        [audio createAudio];
    }
    
    return audio;
}

- (void)createAudio
{
    
    self.AudioPlayer = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenFram.height - 64, ScreenFram.width, 64)];
    self.AudioPlayer.backgroundColor = [UIColor colorWithRed:152/255.0 green:185/255.0 blue:200/255.0 alpha:0.9];
    
    self.AudioImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 15, self.AudioPlayer.frame.size.height - 20, self.AudioPlayer.frame.size.height - 20)];
    self.AudioImageView.layer.masksToBounds = YES;
    self.AudioImageView.layer.cornerRadius = (self.AudioPlayer.frame.size.height - 20)/2;
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    basicAnimation.duration = 4.0;
    [basicAnimation setRepeatCount:NSIntegerMax];
    basicAnimation.fromValue = [NSNumber numberWithFloat:0.0000];
    basicAnimation.toValue = [NSNumber numberWithFloat:2.0000*M_PI];
    [self.AudioImageView.layer addAnimation:basicAnimation forKey:@"rotation"];
    
    [self.AudioPlayer addSubview:self.AudioImageView];
    
    
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 5, ScreenFram.width, 5)];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"iconfont-huakuai.png"] forState:UIControlStateNormal];
    self.progressSlider.maximumTrackTintColor = [UIColor lightGrayColor];
    self.progressSlider.minimumTrackTintColor = [UIColor redColor];
    self.progressSlider.minimumValue = 0.0;
    self.progressSlider.maximumValue = 1.0;
    [self.progressSlider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    
    
    [self.AudioPlayer addSubview:self.progressSlider];
    
    self.soundsTitle = [[UILabel alloc] initWithFrame:CGRectMake(55, 15, 150, 20)];
    self.soundsTitle.font = [UIFont systemFontOfSize:14];
    [self.AudioPlayer addSubview:self.soundsTitle];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 35, 150, 20)];
    self.timeLabel.font = [UIFont systemFontOfSize:14];
    [self.AudioPlayer addSubview:self.timeLabel];
    
    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.leftButton setBackgroundImage:[UIImage imageNamed:@"lastSound_32.png"] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(220, 20, 32, 32);
    [self.leftButton addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    [self.AudioPlayer addSubview:self.leftButton];
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setBackgroundImage:[UIImage imageNamed:@"nextSound_32.png"] forState:UIControlStateNormal];
    self.rightButton.frame = CGRectMake(325, 20, 32, 32);
    [self.rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    [self.AudioPlayer addSubview:self.rightButton];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"play_32.png"] forState:UIControlStateNormal];
    self.playButton.frame = CGRectMake(276, 23, 26, 26);
    [self.playButton addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [self.AudioPlayer addSubview:self.playButton];
    
}

- (void)leftAction
{
    self.audioIndex -= 1;
    if (self.audioArray.count > 0) {
        if (self.audioIndex < 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经是第一首了" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
        } else {
            TracksModel *model = (TracksModel *)[self.audioArray objectAtIndex:self.audioIndex];
            self.timeLabel.text = [NSString stringWithFormat:@"时间：%d:%d", (int)model.duration / 60, (int)model.duration%60];
            [self.AudioImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:nil];
            self.soundsTitle.text = model.title;
            
            [self createStreamer:model.playUrl64 duration:model.duration];
            [self.audioStream start];
            [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause_32.png"] forState:UIControlStateNormal];
        }

    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无播放内容！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
    }
}

- (void)rightAction
{
    self.audioIndex += 1;
    if (self.audioArray.count > 0) {
        if (self.audioIndex < 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经是第一首了" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
        } else {
            TracksModel *model = (TracksModel *)[self.audioArray objectAtIndex:self.audioIndex];
            self.timeLabel.text = [NSString stringWithFormat:@"时间：%d:%d", (int)model.duration / 60, (int)model.duration%60];
            [self.AudioImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:nil];
            self.soundsTitle.text = model.title;
            
            [self createStreamer:model.playUrl64 duration:model.duration];
            [self.audioStream start];
            [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause_32.png"] forState:UIControlStateNormal];
        }
        
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无播放内容！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
    }
}

- (void)playAction
{
    if (self.currentUrl) {
        if ([self.audioStream isPlaying]) {
            [self.audioStream pause];
            [self.playButton setBackgroundImage:[UIImage imageNamed:@"play_32.png"] forState:UIControlStateNormal];
            
        } else if ([self.audioStream isPaused]) {
            [self.audioStream start];
            [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause_32.png"] forState:UIControlStateNormal];
        }
        
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无播放内容！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
    }
}

- (void)sliderAction
{
    [self.audioStream seekToTime:self.progressSlider.value * self.duration];
}

- (void)createStreamer:(NSString *)url duration:(CGFloat)duration
{
    if (url != self.currentUrl || self.isCellSelected) {
        self.currentUrl = url;
        [self destroyStreamer];
        self.duration = duration;
        if (self.duration > 0) {
            [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timeControlAction) userInfo:nil repeats:YES];
        }
        
        TracksModel *model = (TracksModel *)[self.audioArray objectAtIndex:self.audioIndex];
        self.timeLabel.text = [NSString stringWithFormat:@"时间：%2d:%2d", (int)model.duration / 60, (int)model.duration%60];
        [self.AudioImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:nil];
        self.soundsTitle.text = model.title;
        
        NSString *escapedValue =
        (NSString *)(CFURLCreateStringByAddingPercentEscapes(
                                                             nil,
                                                             (CFStringRef)url,
                                                             NULL,
                                                             NULL,
                                                             kCFStringEncodingUTF8)) ;
        ;
        NSURL *url = [NSURL URLWithString:escapedValue];
        self.audioStream = [[AudioStreamer alloc] initWithURL:url];
        self.isCellSelected = NO;
    }
    
}

- (void)timeControlAction
{
    if (self.audioStream.isPlaying) {
        self.progressSlider.value = self.audioStream.progress / self.duration;
    }
}

- (void)pauseStreamer
{
    if (self.audioStream)
    {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:self.audioStream];
        
        [self.audioStream pause];
        self.audioStream = nil;
    }
}

- (void)destroyStreamer
{
    if (self.audioStream)
    {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:self.audioStream];
        
        [self.audioStream stop];
        self.audioStream = nil;
    }
}

@end
